import axios from "axios";
//组件外设置路由的跳转所需工具，主要是响应拦截器401跳转登录页
import { createBrowserHistory } from "history";

import { notification } from 'antd'
import store from '../store'


var history = createBrowserHistory()

//实例化axios
var service = axios.create({
    timeout: 10 * 1000,//响应超时时间
    baseURL: process.env.REACT_APP_BASE_API//设置请求基准路径
})

//设置请求拦截器
service.interceptors.request.use(
    (config) => {
        config.headers['token'] = store.getState().userInfo.token; 
        return config
    },
    (err)=>{
        return Promise.reject(err)
    }
)
//设置响应拦截器
service.interceptors.response.use(
    (res)=>{
        if( res.data.code == '10019' ){
            notification.error({message:'登陆过期,请重新登录!'});
            store.dispatch({ type: 'REMOVE_USERINFO' })
            history.push('/login');
            history.go(0);
        }
        return res
    },
    (err)=>{
        if( err.response.status == 401 ){
            notification.error({message:'登陆过期,请重新登录!'});
            //删除token
            //跳转到登录页
            store.dispatch({ type: 'REMOVE_USERINFO' })
            history.push('/login');
            history.go(0);

        }else if( err.response.status == 404 ){
            notification.error({message:'访问路径有误!'});
        }else if( err.response.status == 500 ){
            notification.error({message:'服务器内部错误!'});
        }else if( err.response.status == 503 ){
            notification.error({message:'服务器无法提供服务!'});
        }

        return Promise.reject(err);
    }
)
export default service